Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: memory & lock issues in sortTransactions #588

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Syn-McJ
Copy link
Member

@Syn-McJ Syn-McJ commented Jan 31, 2025

Issue being fixed or feature implemented

sortTransactions method causes memory spikes on start and deadlocks during sync

What was done?

  • Fix memory issues in sortTransactions
  • Simplify sortTransactions to avoid long locks
  • Remove dead code

How Has This Been Tested?

Breaking Changes

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • Refactor
    • Streamlined wallet balance management by removing redundant historical balance tracking.
    • Enhanced transaction processing with updated sorting for improved efficiency.

@Syn-McJ Syn-McJ requested a review from pankcuf January 31, 2025 04:33
@Syn-McJ Syn-McJ self-assigned this Jan 31, 2025
Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Walkthrough

The changes remove the historical balance tracking from the DSAccount class. In particular, the method for obtaining the balance after a transaction has been removed from both the header and implementation files. Additionally, the balanceHistory property and all associated logic have been eliminated, and the transaction sorting logic has been updated to cache address values locally.

Changes

File Path Change Summary
DashSync/shared/Models/Wallet/DSAccount.h Removed the declaration of the balanceAfterTransaction: method from the DSAccount interface.
DashSync/shared/Models/Wallet/DSAccount.m Removed the balanceHistory property and its associated tracking logic; removed the balanceAfterTransaction: method implementation; updated updateBalance and sortTransactions to simplify processing by caching addresses.

Sequence Diagram(s)

sequenceDiagram
    participant Tx as Transaction
    participant Acc as DSAccount
    Tx ->> Acc: Request balance update
    Acc ->> Acc: Process transaction (removed history tracking)
    Acc ->> Acc: Cache external/internal addresses for sorting
    Acc -->> Tx: Return updated balance
Loading

Poem

I'm a rabbit hopping through the code today,
Skipping old balances that went away.
No more history to weigh my stride,
Simplified sorting keeps me full of pride.
With every commit, my ears stand tall,
For cleaner code makes me hop through it all!
🐰💻


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@@ -289,9 +289,6 @@ FOUNDATION_EXPORT NSString *_Nonnull const DSAccountNewAccountShouldBeAddedFromT
// returns the fee for the given transaction if all its inputs are from wallet transactions, UINT64_MAX otherwise
- (uint64_t)feeForTransaction:(DSTransaction *)transaction;

// historical wallet balance after the given transaction, or current balance if transaction is not registered in wallet
- (uint64_t)balanceAfterTransaction:(DSTransaction *)transaction;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not used anywhere

return NO;
};

NSArray *externalAddresses = self.externalAddresses;
NSArray *internalAddresses = self.internalAddresses;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.externalAddresses and self.internalAddresses was calculated from scratch on every tx comparison

@@ -895,21 +879,22 @@ __block __weak BOOL (^_isAscending)(id, id) = isAscending = ^BOOL(DSTransaction
}] != NSNotFound) return NO;
if ([self.invalidTransactionHashes containsObject:hash1] && ![self.invalidTransactionHashes containsObject:hash2]) return YES;
if ([self.pendingTransactionHashes containsObject:hash1] && ![self.pendingTransactionHashes containsObject:hash2]) return YES;
for (DSTransactionInput *input in tx1.inputs) {
if (_isAscending(self.allTx[uint256_obj(input.inputHash)], tx2)) return YES;
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Precise sorting causes long waits for the lock to be freed, which leads to stalled sync and UI freezes occasionally.
It doesn't look like we need precise sorting anywhere.

@Syn-McJ
Copy link
Member Author

Syn-McJ commented Feb 2, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Feb 2, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
DashSync/shared/Models/Wallet/DSAccount.m (2)

882-882: Consider adding a deterministic fallback for consistent ordering.

Currently, if none of the conditions match, this final return NO; might produce an ambiguous ordering. Consider adding a final comparison step (e.g., comparing transaction hashes) to guarantee stable and deterministic sorting.

-            return NO;
+            // Fallback tiebreak: compare tx hashes
+            NSComparisonResult hashComparison = memcmp(tx1.txHash.u8, tx2.txHash.u8, sizeof(tx1.txHash));
+            if (hashComparison < 0) return YES;
+            if (hashComparison > 0) return NO;
+            return NO; // remain consistent if truly identical

894-895: Clarify the sorting logic when checking internal vs. external addresses.

It's not immediately clear why we look up internalAddresses first for tx1 and partially rely on externalAddresses for tx2. A short explanatory comment or small extract method would improve readability and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 81cec50 and 60ac6c2.

📒 Files selected for processing (2)
  • DashSync/shared/Models/Wallet/DSAccount.h (0 hunks)
  • DashSync/shared/Models/Wallet/DSAccount.m (1 hunks)
💤 Files with no reviewable changes (1)
  • DashSync/shared/Models/Wallet/DSAccount.h
🔇 Additional comments (3)
DashSync/shared/Models/Wallet/DSAccount.m (3)

886-887: Caching addresses in local variables is a good performance measure.

Referencing externalAddresses and internalAddresses in local arrays avoids repeated property lookups in the sorting logic. This also minimizes lock durations, which helps performance.


897-897: Verify symmetrical logic for both transactions.

The code adjusts i if it was not found in internal addresses, but there's no corresponding check for j. This could cause an asymmetrical ordering if tx2 has no internal addresses. Consider ensuring both transactions are handled consistently.


899-899: Confirm reversed numeric comparison is intentional.

The returned result inverts the usual ordering if i > j is treated as ascending. Confirm that this reversed logic suits the domain requirement. If you prefer smaller indices to sort first, swap the return values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant